﻿using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;

namespace MockPrjTeam4.Common
{
    /// <summary>
    /// Lớp sử dụng thực hiện câu lệnh SQL
    /// </summary>
    public sealed class SqlHelper
    {
        private SqlHelper()
        {
        }

        /// <summary>
        /// Execute a stored-procedure with parameter and return IDataReader
        /// </summary>
        /// <param name="storedProcedureName"></param>
        /// <param name="parameterList"></param>
        /// <returns></returns>
        public static IDataReader ExecuteReader(string storedProcedureName, Collection<SqlParameter> parameterList)
        {
            IDataReader result = null;
            try
            {
                //Kết nối
                var connect = new SqlConnection(ApplicationConfig.ConnectionString);
                connect.Open();

                var cmd = new SqlCommand(storedProcedureName, connect) {CommandType = CommandType.Text};
                cmd.Parameters.Clear();
                //Duyệt patameter
                if (parameterList != null)
                {
                    for (int i = 0; i < parameterList.Count; i++)
                    {
                        cmd.Parameters.Add(parameterList[i]);
                    }
                }
                //Thực hiện câu lệnh
                result = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                if (parameterList != null)
                {
                    for (int i = 0; i < parameterList.Count; i++)
                    {
                        if (parameterList[i].Direction == ParameterDirection.Output ||
                            parameterList[i].Direction == ParameterDirection.InputOutput ||
                            parameterList[i].Direction == ParameterDirection.ReturnValue) // if is output
                        {
                            parameterList[i].Value = cmd.Parameters[parameterList[i].ParameterName].Value;
                        }
                    }
                }
                return result;
            }
            catch(SqlException ex)
            {
                //Log lỗi
                if (result != null)
                {
                    result.Close();
                }
                return null;
            }
        }

        /// <summary>
        /// Thực hiện câu lệnh SQL truy vấn
        /// </summary>
        /// <param name="storedProcedureName"></param>
        /// <returns></returns>
        public static IDataReader ExecuteReader(string storedProcedureName)
        {
            IDataReader result = null;
            try
            {
                var connect = new SqlConnection(ApplicationConfig.ConnectionString);
                connect.Open();

                var cmd = new SqlCommand(storedProcedureName, connect) {CommandType = CommandType.Text};
                cmd.Parameters.Clear();

                result = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return result;
            }
            catch(SqlException ex)
            {
                if (result != null)
                {
                    result.Close();
                }
            }
            return result;
        }
        /// <summary>
        /// Thực hiện câu lệnh truy vấn
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static  IDataReader QueryString(string sql)
        {
            IDataReader result = null;
            try
            {
                var connect = new SqlConnection(ApplicationConfig.ConnectionString);
                connect.Open();

                var cmd = new SqlCommand(sql,connect) { CommandType = CommandType.Text};
                result = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return result;
            }
            catch(SqlException)
            {
                if (result != null)
                {
                    result.Close();
                }
                throw;
            }
        }


        /// <summary>
        /// Executes the query.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns></returns>
        public static DataTable ExecuteQuery(string query)
        {
            try
            {
                var result = new DataTable { Locale = CultureInfo.CurrentUICulture };
                var connect = new SqlConnection(ApplicationConfig.ConnectionString);
                connect.Open();
                var cmd = new SqlCommand(query, connect) { CommandType = CommandType.Text };
                cmd.Parameters.Clear();
                var sqlAdapter = new SqlDataAdapter(cmd);
                sqlAdapter.Fill(result);
                connect.Close();
                return result;
            }
            catch(SqlException ex)
            {
                return null;
            }
        }

        /// <summary>
        /// Executes the query with paramter.
        /// </summary>
        /// <param name="storedProcedureName">Name of the stored procedure.</param>
        /// <param name="parameterList">The parameter list.</param>
        /// <returns></returns>
        public static DataTable ExecuteQuery(string storedProcedureName, Collection<SqlParameter> parameterList)
        {
            try
            {
                var result = new DataTable{Locale = CultureInfo.CurrentUICulture};
                var connect = new SqlConnection(ApplicationConfig.ConnectionString);
                connect.Open();

                var cmd = new SqlCommand(storedProcedureName, connect) { CommandType = CommandType.Text };
                cmd.Parameters.Clear();

                if (parameterList != null)
                {
                    for (int i = 0; i < parameterList.Count; i++)
                    {
                        cmd.Parameters.Add(parameterList[i]);
                    }
                }
                var sqlAdapter = new SqlDataAdapter(cmd);
                sqlAdapter.Fill(result);
                connect.Close();
                return result;
            }
            catch(SqlException ex)
            {
                return null;
            }
        }

        /// <summary>
        /// Thực hiện câu lệnh SQL không phải là truy vấn
        /// </summary>
        /// <param name="storedProcedureName"></param>
        /// <param name="parameterList"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string storedProcedureName, Collection<SqlParameter> parameterList)
        {
                var connect = new SqlConnection(ApplicationConfig.ConnectionString);
                connect.Open();

                var cmd = new SqlCommand(storedProcedureName, connect) { CommandType = CommandType.Text };
                cmd.Parameters.Clear();

                if (parameterList != null)
                {
                    for (int i = 0; i < parameterList.Count; i++)
                    {
                        cmd.Parameters.Add(parameterList[i]);
                    }
                }
                int result = cmd.ExecuteNonQuery();

                if (parameterList != null)
                {
                    for (int i = 0; i < parameterList.Count; i++)
                    {
                        if (parameterList[i].Direction == ParameterDirection.Output ||
                            parameterList[i].Direction == ParameterDirection.InputOutput ||
                            parameterList[i].Direction == ParameterDirection.ReturnValue)
                            parameterList[i].Value = cmd.Parameters[parameterList[i].ParameterName].Value;
                    }
                }
                connect.Dispose();
                return result;
        }


        ///<summary>
        /// ExecuteNonQuery
        ///</summary>
        ///<param name="conn">Connection</param>
        ///<param name="connect"></param>
        ///<param name="transaction"></param>
        ///<param name="storedProcedureName">Store procedure</param>
        ///<param name="parameterList">List of parameters</param>
        ///<returns></returns>
        public static int ExecuteNonQuery(SqlConnection connect, SqlTransaction transaction, string storedProcedureName,
                                          Collection<SqlParameter> parameterList)
        {
            var cmd = new SqlCommand(storedProcedureName, connect, transaction) {CommandType = CommandType.Text};
            cmd.Parameters.Clear();

            if (parameterList != null)
            {
                for (int i = 0; i < parameterList.Count; i++)
                {
                    cmd.Parameters.Add(parameterList[i]);
                }
            }
            int result = cmd.ExecuteNonQuery();

            if (parameterList != null)
            {
                for (int i = 0; i < parameterList.Count; i++)
                {
                    if (parameterList[i].Direction == ParameterDirection.Output ||
                        parameterList[i].Direction == ParameterDirection.InputOutput ||
                        parameterList[i].Direction == ParameterDirection.ReturnValue)
                        parameterList[i].Value = cmd.Parameters[parameterList[i].ParameterName].Value;
                }
            }
            return result;
        }

        /// <summary>
        /// ExecuteNonQuery
        /// </summary>
        /// <param name="storedProcedureName"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string storedProcedureName)
        {
            var connect = new SqlConnection(ApplicationConfig.ConnectionString);
            connect.Open();

            var cmd = new SqlCommand(storedProcedureName, connect) {CommandType = CommandType.Text};
            cmd.Parameters.Clear();
            int result = cmd.ExecuteNonQuery();
            connect.Dispose();
            return result;
        }

        ///<summary>
        ///</summary>
        ///<param name="connect"></param>
        ///<param name="transaction"></param>
        ///<param name="storedProcedureName">Store procedure</param>
        ///<returns></returns>
        public static int ExecuteNonQuery(SqlConnection connect, SqlTransaction transaction, string storedProcedureName)
        {
            var cmd = new SqlCommand(storedProcedureName, connect, transaction) {CommandType = CommandType.Text};
            cmd.Parameters.Clear();
            int result = cmd.ExecuteNonQuery();
            return result;
        }


        /// <summary>
        /// Executes the data adapter.
        /// </summary>
        /// <param name="store">The store.</param>
        /// <returns></returns>
        public static DataTable ExecuteDataAdapter(string store)
        {
            var table = new DataSet();
            table.Locale = CultureInfo.InvariantCulture;
            var conn = new SqlConnection(ApplicationConfig.ConnectionString);
            var adapter = new SqlDataAdapter(store, conn);
            adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
            adapter.Fill(table);
            return table.Tables[0];
        }

        /// <summary>
        /// Executes the data adapter.
        /// </summary>
        /// <param name="store">The store.</param>
        /// <param name="parameterList">The parameter list.</param>
        /// <returns></returns>
        public static DataTable ExecuteDataAdapter(string store, Collection<SqlParameter> parameterList)
        {
            var table = new DataSet();
            table.Locale = CultureInfo.InvariantCulture;
            var conn = new SqlConnection(ApplicationConfig.ConnectionString);
            var adapter = new SqlDataAdapter(store, conn);
            adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
            if (parameterList != null)
            {
                for (int i = 0; i < parameterList.Count; i++)
                {
                    adapter.SelectCommand.Parameters.Add(parameterList[i]);
                }
            }
            adapter.Fill(table);
            if (parameterList != null)
            {
                for (int i = 0; i < parameterList.Count; i++)
                {
                    if (parameterList[i].Direction == ParameterDirection.Output ||
                        parameterList[i].Direction == ParameterDirection.InputOutput ||
                        parameterList[i].Direction == ParameterDirection.ReturnValue)
                        parameterList[i].Value = adapter.SelectCommand.Parameters[parameterList[i].ParameterName].Value;
                }
            }
            return table.Tables[0];
        }
    }
}